<template>
    <view class="chat-container">
        <u-notice-bar mode="horizontal" :show="showTips" :list="listTips"></u-notice-bar>
        <z-paging
            ref="paging"
            v-model="dataList"
            :style="{ paddingTop: showTips ? '80rpx' : '' }"
            use-chat-record-mode
            use-virtual-list
            cell-height-mode="dynamic"
            safe-area-inset-bottom
            bottom-bg-color="#f8f8f8"
            empty-view-text="欢迎咨询"
            @query="getUserChatMsgList"
            @keyboardHeightChange="keyboardHeightChange"
            @hidedKeyboard="hidedKeyboard"
        >
            <!-- 注意不要直接在chat-item组件标签上设置style，因为在微信小程序中是无效的，请包一层view -->
            <template #cell="{ item, index }">
                <view style="transform: scaleY(-1)">
                    <chat-item :item="item"></chat-item>
                </view>
            </template>
            <!-- 底部聊天输入框 -->
            <template #bottom>
                <chat-input-bar ref="inputBar" @send="(msg) => sendChat(1, msg)">
                    <view slot="prefix" class="choose-image">
                        <image src="/static/add-rich.png" @click="chooseImage(['album'])"></image>
                    </view>
                </chat-input-bar>
            </template>
            <template v-if="isNotBusinessTime">
                <u-alert-tips
                    close-able
                    @close="HandleCloseAlertTips"
                    style="transform: scaleY(-1); margin: 20rpx 40rpx"
                    type="warning"
                    title="温馨提示"
                    :description="description"
                ></u-alert-tips>
            </template>
        </z-paging>
        <view class="goods_short" v-if="shortcutShow">
            <image class="goods_image" :src="shortcutImage" style="width: 110rpx; height: 110rpx"></image>
            <view class="goods_detail">
                <view class="goods_title">
                    <span v-if="shortcutShow === 'order'" class="order_title">订单编号：{{ shortcutID }}</span>
                    <template v-else>{{ shortcutTitle }}</template>
                </view>
                <view v-if="shortcutShow === 'order'" class="time">订单时间：{{ shortcutCreateTime }}</view>
                <view class="goods_price" style="color: #ed5732; font-size: 34rpx">
                    ￥{{ shortcutMoney }}
                    <span v-if="shortcutShow === 'order'" class="order_num">x{{ shortcutNum }}</span>
                </view>
            </view>
            <view style="text-align: right">
                <image @click="goodsShortClose" src="/static/RICHbillDetail/RICHclose.png" style="width: 25rpx; height: 25rpx"></image>
                <view class="action" @click="goodsShortSendChat">发送</view>
            </view>
        </view>
    </view>
</template>

<script>
import { wssHost } from '@/utils/constant.js';
import ChatInputBar from './chat-input-bar.vue';
import ChatItem from './chat-item.vue';
import defaultStoreHead from '@/static/tenant/logo.png';
import defaultUserHead from '@/static/0.png';
import { getZWZUserDetail } from '@/utils/index';
export default {
    components: {
        ChatInputBar,
        ChatItem
    },
    data() {
        return {
            connected: false,
            isNotBusinessTime: false,
            connecting: false,
            chatId: '',
            agentId: '',
            shopId: '',
            tenantId: '',
            dataList: [],
            shortcutShow: '',
            shortcutID: '',
            shortChannel: '',
            shortcutImage: '',
            shortcutNum: '',
            shortcutMoney: '',
            shortcutSales: '',
            shortcutTitle: '',
            shortcutCreateTime: '',
            className: '',
            store: {},
            heartbeatInterval: null,
            heartbeatTimeoutId: null,
            showTips: false,
            listTips: [
                '尊敬的客户您好，非常抱歉',
                '由于我们的客服时间是早8:30到晚20:00',
                '您现在发送消息可能无人及时应答',
                '我们非常期待您在客服时间来咨询',
                '我们将真诚为您服务。'
            ],
            description: '客服工作时间：9-18点，订单待审核的客户，到时客服会联系您，请保持电话畅通！'
        };
    },
    onUnload() {
        this.clearHeartbeat();
        uni.closeSocket();
        uni.removeStorageSync('store');
        uni.hideLoading();
        uni.removeStorage({
            key: 'product'
        });
        uni.removeStorage({
            key: 'order'
        });
        uni.removeStorageSync('haveCloseAlertTips');
    },
    onLoad(d) {
        this.checkoutCustomTime();
        // 咨询订单或者商品
        const product = uni.getStorageSync('product');
        const order = uni.getStorageSync('order');
        if (product) {
            const productObj = JSON.parse(product);
            this.shortcutShow = 'product';
            this.shortcutID = productObj.goodsId;
            this.shortcutImage = productObj.image;
            this.shortcutMoney = productObj.price;
            this.shortcutTitle = productObj.name;
        } else if (order) {
            const orderObj = JSON.parse(order);
            this.shortcutShow = 'order';
            this.shortcutID = orderObj.orderId;
            this.shortcutTitle = orderObj.name;
            this.shortcutImage = orderObj.image;
            this.shortcutMoney = orderObj.price;
            this.shortcutNum = orderObj.orderNum;
            this.shortcutCreateTime = orderObj.createTime;
        } else {
            this.shortcutShow = '';
        }
        this.shopId = d.shopId;
        if (this.shopId === 'null' || this.shopId === 'undefined') {
            this.shopId = '';
        }
        let userId = this.$getUid();
        if (!userId) {
            this.$goLogin();
            return;
        }
        // 会话ID，用来创建聊天窗体
        this.sessionId = userId;
        this.tenantId = uni.getStorageSync('tenantId');
        this.startChat();
		
		console.log('当前时间',new Date().getHours());
		if(new Date().getHours()<9 && new Date().getHours()>17){
			//9：00-18：00才有客服，超出这个时间就出现弹窗
			console.log('有弹窗');
			this.isNotBusinessTime=true
		}else{
			console.log('没有弹窗');
			this.isNotBusinessTime=false
		}
    },
    methods: {
        startChat() {
            this.chatSave().then(() => this.getUserChatMsgList(1, 10));
            this.connect();
            uni.setNavigationBarTitle({
                title: this.agentName || '在线客服'
            });
        },
        reconnect() {
            this.clearHeartbeat();
            this.connecting = false;
            this.connected = false;
            uni.closeSocket();
            uni.hideLoading();
            this.connect();
        },
        connect() {
            if (this.connected || this.connecting) {
                console.log('已连接');
                return;
            }
            this.connecting = true;
            uni.connectSocket({
                method: 'GET',
                url: wssHost + '/mall-business/websocket/' + this.sessionId,
                header: {
                    'content-type': 'application/json'
                },
                data() {
                    return {
                        msg: 'Hello'
                    };
                },
                success: (res) => {
                    console.log('接口调用成功', wssHost + '/websocket/' + this.sessionId);
                    // 这里是接口调用成功的回调，不是连接成功的回调，请注意
                },
                fail(err) {
                    // 这里是接口调用失败的回调，不是连接失败的回调，请注意
                }
            });
            uni.onSocketOpen((res) => {
                this.connecting = false;
                this.connected = true;
                uni.hideLoading();
                this.startHeartbeat();
            });
            uni.onSocketError((err) => {
                this.connecting = false;
                this.connected = false;
                uni.hideLoading();
                clearInterval(this.heartbeatInterval);
                uni.showModal({
                    content: '网络较差，请稍后再试',
                    showCancel: false
                });
            });
            uni.onSocketMessage((res) => {
                console.log('收到服务器内容：', res);
                if (res.data === 'pong') {
                    // 如果收到pong消息，重置超时定时器
                    this.clearHeartbeat();
                    this.startHeartbeat();
                    return;
                }
                res.data = JSON.parse(res.data);

                if (res.data.isNotBusinessTime) {
                    let flag = uni.getStorageSync('haveCloseAlertTips');
                    if (!flag) {
                        // this.isNotBusinessTime = true;
                        // this.description = res.data.msg;
                    }
                    return;
                }
                if (res.data.version && res.data.packetId) {
                    return;
                }
                this.$refs.paging.addChatRecordData(this.creatRecordChatItem(res.data));
            });
            uni.onSocketClose((res) => {
                this.connected = false;
                clearInterval(this.heartbeatInterval);
            });
        },
        close() {
            uni.closeSocket();
        },
        startHeartbeat() {
            // 设置心跳间隔，例如每20秒发送一次心跳
            this.heartbeatInterval = setInterval(() => {
                console.log('发送心跳消息');
                let userId = uni.getStorageSync('uid');
                let data = {
                    userId,
                    content: 'ping',
                    sendType: '1'
                };
                uni.sendSocketMessage({
                    data: JSON.stringify(data)
                });
            }, 20000);
            // 设置超时处理
            this.heartbeatTimeoutId = setTimeout(() => {
                console.log('在规定时间内没有收到pong消息，则认为连接已断开,执行重连逻辑');
                this.connect();
            }, 50000);
        },
        clearHeartbeat() {
            if (this.heartbeatInterval) {
                clearInterval(this.heartbeatInterval);
            }
            if (this.heartbeatTimeoutId) {
                clearInterval(this.heartbeatTimeoutId);
            }
        },
        creatRecordChatItem(d = {}) {
            d.time = d.time || d.createTime || '';
            if (d.type === 4 || d.type === 3) {
                d.content = d.content.split(',');
            }
            d.isMe = d.isMe || d.sendType === 1;
            const userDetail = getZWZUserDetail();
            let userName = userDetail.userName || userDetail.nickName;
            let userHead = userDetail.avatar || defaultUserHead;
            let agentName = this.agentName || this.$appNameDict[this.$appName] + '官方客服';
            let agentHead = this.agentHead || defaultStoreHead;
            if (d.chat) {
                agentName = d.chat.agentName || agentName;
                agentHead = d.chat.agentHead || agentHead;
                userName = d.chat.userName || userName;
                userHead = d.chat.userHead || userHead;
            }
            d.icon = d.icon || (d.isMe ? userHead : agentHead);
            d.name = d.name || (d.isMe ? userName : agentName);
            return d;
        },
        getUserChatMsgList(pageNum, pageSize) {
            let chatId = this.chatId;
            console.log(chatId, pageNum, pageSize);
            if (!chatId || !pageNum || !pageSize) {
                uni.hideLoading();
                return;
            }
            return this.$request(this.$baseHost + '/mall-business/chatContent/userList', { chatId, pageNum, pageSize }, 'get')
                .then((res) => {
                    if (res.code === 200) {
                        const list = res.result.list || [];
                        const chatContentList = list.map((item) => this.creatRecordChatItem(item));
                        this.$refs.paging.complete(chatContentList);
                    }
                    uni.hideLoading();
                })
                .catch((res) => {
                    this.$refs.paging.complete(false);
                });
        },
        chatSave() {
            const userDetail = getZWZUserDetail();
            console.log(12121, getZWZUserDetail());
            let userId = uni.getStorageSync('uid');
            let data = {
                userId,
                userName: userDetail.userName || userDetail.nickName,
                userHead: userDetail.avatar || '',
                tenantId: this.tenantId,
                shopId: userDetail.shopId || this.shopId
            };
            return this.$request(this.$baseHost + '/mall-business/chat/save', data, 'post').then((res) => {
                if (res.code === 200) {
                    this.chatId = res.result.chatId;
                    this.agentId = res.result.agentId;
                }
            });
        },
        checkoutCustomTime() {
            let startHour = 8;
            let startMinute = 30;
            let endHour = 20;
            let endMinute = 0;
            const date = new Date();
            let currentHour = date.getHours();
            let currentMinute = date.getMinutes();
            console.log(currentHour, currentMinute);
            this.showTips = false;
            if (currentHour < startHour || (currentHour == 8 && currentMinute < startMinute)) {
                this.showTips = true;
            }
            if (currentHour > endHour || (currentHour == 20 && currentMinute > endMinute)) {
                this.showTips = true;
            }
        },
        sendChat(type, content) {
            this.checkoutCustomTime();
            //type:1文字 2图片 3订单
            if (!content) {
                uni.showToast({
                    title: '请输入聊天内容'
                });
                return;
            }
            if (!this.chatId) {
                return;
            }
            if (type == 4) {
                content = `${this.shortcutImage},${this.shortcutTitle},${this.shortcutMoney},${this.shortcutID}`;
            }
            if (type == 3) {
                content = `${this.shortcutImage},${this.shortcutTitle},${this.shortcutID},${this.shortcutNum},${this.shortcutCreateTime},${this.shortcutMoney}`;
            }
            let userId = uni.getStorageSync('uid');
            const userDetail = getZWZUserDetail();
            let data = {
                userId,
                content,
                chatId: this.chatId,
                type,
                agentId: this.agentId,
                shopId: userDetail.shopId || this.shopId,
                tenantId: this.tenantId,
                sendType: '1'
            };
            console.log(data);
            data = JSON.stringify(data);
            let that = this;
            uni.sendSocketMessage({
                data: data,
                success(res) {
                    that.$refs.paging.addChatRecordData(
                        that.creatRecordChatItem({
                            time: that.formatDate(),
                            icon: '',
                            name: '',
                            content,
                            type,
                            sendType: 1,
                            chat: ''
                        })
                    );
                    that.$refs.inputBar.focus = true;
                },
                fail(err) {
                    console.log(err);
                    this.reconnect();
                }
            });
            that.content = '';
        },
        formatDate: function (now) {
            now = now || new Date();
            const year = now.getFullYear();
            const month = now.getMonth() + 1;
            const date = now.getDate();
            const hour = now.getHours();
            const minutes = now.getMinutes();
            const seconds = now.getSeconds();
            return `${year}-${month}-${date} ${hour}:${minutes}:${seconds}`;
        },
        scrollToBottom() {
            this.$nextTick(() => {
                uni.pageScrollTo({
                    scrollTop: 100000,
                    duration: 300
                });
            });
        },
        // 发送图片
        chooseImage(sourceTsend) {
            const that = this;
            uni.chooseImage({
                count: 1,
                sourceType: ['album'],
                success: (res) => {
                    uni.showLoading({
                        title: '文件正在全力上传中，请耐心等待'
                    });
                    const tempFilePaths = res.apFilePaths || res.tempFilePaths || res.tempFiles;
                    this.$fileUploadHandler(tempFilePaths[0], function (data) {
                        uni.hideLoading();
                        var imgUrls = JSON.parse(data.data).data;
                        that.sendChat(2, imgUrls);
                        uni.hideLoading();
                    });
                }
            });
        },
        // 监听键盘高度改变，请不要直接通过uni.onKeyboardHeightChange监听，否则可能导致z-paging内置的键盘高度改变监听失效（如果不需要切换表情面板则不用写）
        keyboardHeightChange(res) {
            this.$refs.inputBar.updateKeyboardHeightChange(res);
        },
        // 用户尝试隐藏键盘，此时如果表情面板在展示中，应当通知chatInputBar隐藏表情面板（如果不需要切换表情面板则不用写）
        hidedKeyboard() {
            this.$refs.inputBar.hidedKeyboard();
        },
        goodsShortClose() {
            this.shortcutShow = '';
            uni.removeStorage({
                key: 'product'
            });
            uni.removeStorage({
                key: 'order'
            });
        },
        goodsShortSendChat() {
            //  3是订单 4商品
            let type = this.shortcutShow === 'product' ? 4 : 3;
            this.sendChat(type, true);
            this.goodsShortClose();
        },
        copy(content) {
            uni.showModal({
                title: '温馨提示',
                content: '确认要复制此文字吗',
                showCancel: true,
                cancelText: '取消',
                confirmText: '确认',
                success: (res) => {
                    if (res.confirm) {
                        uni.setClipboardData({
                            data: content,
                            success: (r) => {
                                uni.showToast({
                                    title: '复制成功'
                                });
                            }
                        });
                    }
                }
            });
        },
        h5Copy(content) {
            if (!document.queryCommandSupported('copy')) {
                // 不支持
                return false;
            }
            let textarea = document.createElement('textarea');
            textarea.value = content;
            textarea.readOnly = 'readOnly';
            document.body.appendChild(textarea);
            textarea.select(); // 选择对象
            textarea.setSelectionRange(0, content.length); //核心
            let result = document.execCommand('copy'); // 执行浏览器复制命令
            textarea.remove();
            return result;
        },
        HandleCloseAlertTips() {
            this.isNotBusinessTime = false;
            uni.setStorageSync('haveCloseAlertTips', true);
        }
    }
};
</script>

<style lang="scss" scoped>
page {
    background-color: #fff;
}
.u-notice-bar-wrap {
    position: fixed;
    z-index: 999;
}
/deep/.zp-page-bottom-container {
    .chat-input-bar-container {
        position: relative;
        .chat-input-bar {
            padding-left: 100rpx;
        }
        .choose-image {
            position: absolute;
            border-radius: 10rpx;
            top: 18rpx;
            left: -2rpx;
            height: 67rpx;
            width: 67rpx;
            margin-left: 20rpx;
            background-color: #fff;
            image {
                width: 100%;
                height: 100%;
                transform: scale(0.8);
            }
        }
    }
}

.input-box {
    position: fixed;
    bottom: 0;
    left: 0;
    height: 100rpx;
    width: 100%;
    display: flex;
    box-sizing: content-box;
    z-index: 999;
    background-color: #ececec;
    padding: 5rpx;
}

.chat-listitem {
    display: flex;
    margin-top: 20rpx;
    padding: 10rpx;
}

.chat-listitem-text {
    color: #000000;
    background: #ffffff;
    margin-top: 10rpx;
    width: fit-content;
    padding: 15rpx;
    font-size: 30rpx;
    height: max-content;
    word-wrap: break-word;
    word-break: break-all;
    border-radius: 10rpx;
}
.chat-listitem-image {
    margin-top: 5rpx;
    width: 75rpx;
    height: 75rpx;
    border-radius: 5rpx;
}

.save {
    width: 130rpx;
    text-align: center;
    border-radius: 10rpx;
    height: 70rpx;
    background: #ffffff;
    margin: 5rpx 10rpx 0;
    line-height: 70rpx;
}

.chat-item {
    display: flex;
    flex-direction: column;
}

.goods_short {
    min-height: 150upx;
    position: fixed;
    bottom: 120upx;
    z-index: 99;
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 20rpx;
    box-shadow: 0 0 20rpx 0 rgba(0, 0, 0, 0.2);
    display: flex;
    width: 94%;
    color: #000000;
    padding: 20rpx;
    margin: 0 3%;
    justify-content: space-between;
    .goods_detail {
        margin-left: 20rpx;
        width: 400rpx;
        display: flex;
        justify-content: space-between;
        flex-direction: column;
    }
    .goods_title {
        font-size: 34rpx;
        color: #000000;
        overflow: hidden;
        text-overflow: ellipsis;
        flex-wrap: nowrap;
        white-space: nowrap;
        width: 98%;
        .order_title {
            font-size: 24rpx;
        }
    }
    .goods_price {
        .order_num {
            margin-left: 10rpx;
            font-size: 24rpx;
            color: #333;
        }
    }
    .time {
        font-size: 24rpx;
    }
    .action {
        margin-top: 30rpx;
        background: #f9221d;
        color: #ffffff;
        border-radius: 50rpx;
        width: auto;
        padding: 0 30rpx;
        white-space: nowrap;
        height: 50rpx;
        font-size: 24rpx;
        text-align: center;
        line-height: 50rpx;
    }
}
</style>
